package com.bigfans.catalogservice.api.mgr;

import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.plugins.FileStoragePlugin;
import com.bigfans.framework.plugins.UploadResult;
import com.bigfans.framework.utils.WebUtils;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author lichong
 * @create 2018-03-14 下午7:51
 **/
@RestController
public class ProductImageManageApi extends BaseController {

    @Autowired
    private FileStoragePlugin fileStoragePlugin;

    @PostMapping(value = "/uploadProductImg")
    @NeedLogin(roles = {"operator", "admin"})
    public RestResponse uploadImg(@RequestParam("file") MultipartFile image) throws Exception {
        String ext = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
        String tempName = UUID.randomUUID().toString() + "." + ext;
        File tempFolder = new File(WebUtils.getWebDiskTempPath());
        if (!tempFolder.exists()) {
            tempFolder.mkdirs();
        }
        File tempFile = new File(tempFolder, tempName);
        image.transferTo(tempFile);
        try{
            UploadResult uploadResult = fileStoragePlugin.upload(tempFile, "/product/" + tempName);
            Map<String, Object> data = new HashMap<>();
            data.put("storageType", uploadResult.getStorageType());
            data.put("filePath", uploadResult.getFilePath());
            data.put("fileKey", uploadResult.getFileKey());
            return RestResponse.ok(data);
        } finally {
            tempFile.deleteOnExit();
        }
    }

    @PostMapping(value = "/removeProductImg")
    public RestResponse removeImg(@RequestBody Map<String, Object> params) throws Exception {
        UploadResult uploadResult = fileStoragePlugin.deleteFile((String) params.get("file"));
        return RestResponse.ok(uploadResult);
    }

    protected String getUploadFileExt(MultipartFile file) {
        return file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
    }

}
